import 'package:environmental_les_app/common/routes/route_names.dart';
import 'package:environmental_les_app/common/style/colours.dart';
import 'package:environmental_les_app/common/style/font_style.dart';
import 'package:environmental_les_app/common/widgets/aqi_card_widget.dart';
import 'package:environmental_les_app/common/widgets/rich_text.dart';
import 'package:environmental_les_app/common/widgets/top_screen_widget.dart';
import 'package:environmental_les_app/page/main/home/widgets/clue_item.dart';
import 'package:environmental_les_app/page/main/home/widgets/event_item.dart';
import 'package:environmental_les_app/page/main/home/widgets/task_item.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});

  // 主视图
  Widget _buildView() {
    return NotificationListener(
      onNotification: (ScrollNotification note) {
        /// 确保是垂直方向滚动，且滑动至底部
        if (note.metrics.pixels == note.metrics.maxScrollExtent &&
            note.metrics.axis == Axis.vertical &&
            !controller.loadMore) {
          logger.e("滑动到了最底部");
        }
        return true;
      },
      child: Stack(
        children: [
          Container(
            height: 255,
            decoration: BoxDecoration(
                image: DecorationImage(
              image: AssetImage(ImageUtils.getImgPath("bg_home_top")),
              fit: BoxFit.cover,
            )),
          ),
          SafeArea(
            child: EasyRefresh.builder(
              onRefresh: controller.onRefresh,
              header: const TaurusHeader(skyColor: Colours.bgE6F2FE),
              childBuilder: (context, physics) {
                return CustomScrollView(
                  physics: physics,
                  controller: controller.scrollController,
                  slivers: [
                    SliverToBoxAdapter(
                      child: _buildTitle(),
                    ),
                    SliverToBoxAdapter(
                      child: _buildAqi(),
                    ),
                    _buildTodoTab(),
                    SliverToBoxAdapter(
                      child: _buildTodoList(),
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeController>(
      init: HomeController(),
      id: "home",
      builder: (_) {
        return Scaffold(
          body: _buildView(),
        );
      },
    );
  }

  // 首页Title widget
  Widget _buildTitle() {
    return Container(
      padding: const EdgeInsets.only(
        top: 10,
      ),
      child: Row(
        children: [
          hGap15,
          Text(
            "首页",
            style: FontStyles.homeTitle,
          ),
          const Spacer(),
          Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.all(4.0),
            decoration: BoxDecoration(
              color: Colours.bgECF5FF,
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white,
                width: 1,
              ),
            ),
            height: 36,
            width: 36,
            child: Stack(
              children: [
                ImageWidget.loadAssetImage("ic_home_msg",
                    width: 20.0, height: 20.0),
                const Positioned(
                  right: 0,
                  top: 0,
                  child: GFBadge(
                    shape: GFBadgeShape.circle,
                    size: 10,
                  ),
                )
              ],
            ),
          ),
          hGap15,
        ],
      ),
    );
  }

  // 首页AQI widget
  Widget _buildAqi() {
    return Column(
      children: [
        Row(
          children: [
            hGap15,
            Text(
              "更新时间：2025/08/19 16:12:15",
              style: FontStyles.textCustom09c(14),
            ),
          ],
        ),
        const AqiCard(
          aqiValue: 126,
          showMore: true,
          primaryPollutant: "PM2.5",
          pollutantValue: {
            "pm25": 106,
            "pm10": 106,
            "o3": 56,
            "no2": 32,
            "so2": 12,
            "co": 0.8
          },
        ),
      ],
    );
  }

// 首页 待办tab widget
  Widget _buildTodoTab() {
    return SliverAppBar(
      floating: false,
      automaticallyImplyLeading: false,
      pinned: true,
      elevation: 0.0,
      toolbarHeight: 90.0,
      expandedHeight: 90.0,
      backgroundColor: Colors.transparent,
      flexibleSpace: Container(
        decoration: const BoxDecoration(
          color: Colours.bgE6F2FE,
          border: Border(
            top: BorderSide(
              color: Colors.white,
              width: 1.0,
            ),
            left: BorderSide(
              color: Colors.white,
              width: 1.0,
            ),
            right: BorderSide(
              color: Colors.white,
              width: 1.0,
            ),
          ),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.0),
            topRight: Radius.circular(10.0),
          ),
        ),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.only(top: 10, bottom: 10),
              child: Row(
                children: [
                  hGap10,
                  RichTextWidget(children: [
                    TextSpan(
                      text: "待办任务 共",
                      style: FontStyles.textCustom969(14),
                    ),
                    const TextSpan(
                      text: "20",
                      style: TextStyle(
                        color: Colours.appMain,
                        fontWeight: FontWeight.w600,
                        fontSize: 15,
                      ),
                    ),
                    TextSpan(
                      text: " 项",
                      style: FontStyles.textCustom969(14),
                    ),
                  ]),
                ],
              ),
            ),
            Container(
              decoration: const BoxDecoration(
                color: Colours.bgColor,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.0),
                  topRight: Radius.circular(10.0),
                ),
              ),
              child: TabBar(
                controller: controller.tabController,
                tabs: controller.tabs
                    .map((e) => Tab(height: 44, text: e))
                    .toList(),
                onTap: (index) => controller.onTabClick(index),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 首页待办任务 widget
  Widget _buildTodoList() {
    if (controller.tabClickIndex == 0) {
      return _buildClueList();
    } else if (controller.tabClickIndex == 1) {
      return _buildTaskList();
    } else {
      return _buildEventList();
    }
  }

  // 任务列表
  Widget _buildTaskList() {
    return Column(
      children: [
        vGap10,
        TopScreenWidget(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(6)),
          ),
          margin: const EdgeInsets.only(right: 10, left: 0, top: 0, bottom: 0),
          padding:
              const EdgeInsets.only(right: 10, left: 10, top: 6, bottom: 6),
          filterData: controller.taskFilter,
          initialSelected: controller.taskSelectedFilters,
          onSelectionChanged: (selected) {
            // selected is Map<String, List<String>>?
            if (selected == null) {
              controller.updateTaskSelection(null);
            } else {
              // controller.updateSelection accepts Map<String, dynamic>? where values may be List
              controller
                  .updateTaskSelection(selected.map((k, v) => MapEntry(k, v)));
            }
          },
        ),
        ListView.builder(
          itemCount: controller.todoList.length,
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return TaskItem(item: controller.todoList[index]);
          },
        ),
        _buildBottomView("待办任务", () {
          Get.toNamed(AppRoutes.taskListPage);
        }),
      ],
    );
  }

  // 线索列表
  Widget _buildClueList() {
    return Column(
      children: [
        vGap10,
        TopScreenWidget(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(6)),
          ),
          margin: const EdgeInsets.only(right: 10, left: 0, top: 0, bottom: 0),
          padding:
              const EdgeInsets.only(right: 10, left: 10, top: 6, bottom: 6),
          filterData: controller.clueFilter,
          initialSelected: controller.clueSelectedFilters,
          onSelectionChanged: (selected) {
            // selected is Map<String, List<String>>?
            if (selected == null) {
              controller.updateClueSelection(null);
            } else {
              // controller.updateSelection accepts Map<String, dynamic>? where values may be List
              controller
                  .updateClueSelection(selected.map((k, v) => MapEntry(k, v)));
            }
          },
        ),
        ListView.builder(
          itemCount: controller.todoList.length,
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return ClueItem(item: controller.todoList[index]);
          },
        ),
        _buildBottomView("报警线索", () {
          Get.toNamed(AppRoutes.warningListPage);
        }),
      ],
    );
  }

  // 事件列表
  Widget _buildEventList() {
    return Column(
      children: [
        vGap10,
        TopScreenWidget(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(6)),
          ),
          margin: const EdgeInsets.only(right: 10, left: 0, top: 0, bottom: 0),
          padding:
              const EdgeInsets.only(right: 10, left: 10, top: 6, bottom: 6),
          filterData: controller.eventFilter,
          initialSelected: controller.eventSelectedFilters,
          onSelectionChanged: (selected) {
            // selected is Map<String, List<String>>?
            if (selected == null) {
              controller.updateEventSelection(null);
            } else {
              // controller.updateSelection accepts Map<String, dynamic>? where values may be List
              controller
                  .updateEventSelection(selected.map((k, v) => MapEntry(k, v)));
            }
          },
        ),
        ListView.builder(
          itemCount: controller.todoList.length,
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return EventItem(item: controller.todoList[index]);
          },
        ),
        _buildBottomView("巡查事件", () {
          Get.toNamed(AppRoutes.eventListPage);
        }),
      ],
    );
  }

  // 底部查看所有列表
  Widget _buildBottomView(String type, void Function()? onTap) {
    return Container(
      margin: const EdgeInsets.only(top: 10, bottom: 40),
      child: InkWell(
        onTap: onTap,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("查看所有$type",
                style:
                    const TextStyle(color: Colours.color1F59EF, fontSize: 14)),
            hGap8,
            const Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colours.color1F59EF,
            )
          ],
        ),
      ),
    );
  }
}
